package com.example.roam.ui.activity;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.example.roam.R;
import com.example.roam.model.UserEntity;
import com.example.roam.model.gson.User;
import com.example.roam.utils.Constans;
import com.example.roam.utils.HttpUtil;
import com.example.roam.utils.Md5Util;
import com.example.roam.utils.SizeUtils;
import com.example.roam.utils.StatusBarUtils;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Response;

//登录页
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btnlogin;
    private Button btnregister;
    private Button btnforget;
    private EditText edit1;
    private EditText edit2;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.purple_500);//设置状态栏颜色为银白色
        requestPermission(); // 获取外部存储的读取和写入权限
        btnlogin = (Button) findViewById(R.id.button1);
        btnregister = (Button) findViewById(R.id.button2);
        btnforget = (Button) findViewById(R.id.button3);
        edit1 = (EditText) findViewById(R.id.edit1);
        edit2 = (EditText) findViewById(R.id.edit2);
//        edit1.setText("nameundefind@163.com");
//        edit2.setText("123123");
        edit1.setText("1215447720@qq.com");
        edit2.setText("123123");
        btnforget.setOnClickListener(this);
        btnregister.setOnClickListener(this);
        btnlogin.setOnClickListener(this);
        Constans.DISPLAY_WIDTH_PX = SizeUtils.scalePx(this).widthPixels;
        Constans.DISPLAY_HEIGHT_PX = SizeUtils.scalePx(this).heightPixels;
        Constans.SCALE_WIDTH = Constans.DISPLAY_WIDTH_PX / 1080.0;
        Constans.SCALE_HEIGHT = Constans.DISPLAY_HEIGHT_PX / 1794.0;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                String userName = edit1.getText().toString().trim();
                String password = edit2.getText().toString().trim();
                // nameundefind@163.com 123123
//                 1215447720@qq.com 123123
                try {
                     password = Md5Util.encodeByMd5(password+Constans.SALT);
                    Log.i(TAG, "onClick: md5 ->"+password);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String url = "http://47.108.249.115:8080/LuShuDao0.0.2-1.0-SNAPSHOT/UserInfo/loginUser";
                FormBody formBody = new FormBody.Builder().add("userAcc",userName).add("userPwd",password).build();
                HttpUtil.getPostResponse(url, formBody, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        System.out.println("失败！");
                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        user = new Gson().fromJson(response.body().string(), User.class);
                        Log.i(TAG, "onResponse: user:"+user);
                        // 4情况： 1. 用户登录成功，2. 用户名或密码错误 3. 不存在该用户 4.服务器异常
                        loginLogic(LoginActivity.this.user);
                    }
                });
                break;
            case R.id.button2:
                Intent intent1 = new Intent(LoginActivity.this,
                        RegisterActivity.class);
                startActivity(intent1);
                break;
            case R.id.button3:
                Intent intent2 = new Intent(LoginActivity.this,
                        ForgetPasswordActivity.class);
                startActivity(intent2);
                break;
        }
    }
  // nameundefind@163.com 123123
    //判断邮箱是否合法
    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }
    public void requestPermission() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != 0) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10);
            }
        }
    }
    public void loginLogic(User user){
        LoginActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(user.getMessage().equals("没有该用户")){
                    Toast.makeText(LoginActivity.this,"不存在该用户！",Toast.LENGTH_SHORT).show();
                }else if( user.getMessage().equals("密码错误")){
                    Toast.makeText(LoginActivity.this,"用户名或密码错误！",Toast.LENGTH_SHORT).show();
                }else if( user.getMessage().equals("成功")){
//                    Toast.makeText(LoginActivity.this,"登录成功！",Toast.LENGTH_SHORT).show();
//                    Runner runner = new Runner();
//                    runner.start();
                    UserEntity userEntity = user.getData().getUserEntity();
                    // 第一次注册
                    if( userEntity.getU_username() == null || userEntity.getU_username().equals("") ){
                        initConstantsFirst(userEntity);
                        initSharedPreferencesFirst(userEntity);
                        Intent intent = new Intent(LoginActivity.this,InformationActivity.class);
                        startActivity(intent);
                    }else { // 不是第一次注册
                        initConstants(userEntity);
                        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                        startActivity(intent);

                    }
                }else {
                    Toast.makeText(LoginActivity.this,"服务器异常！",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void initConstantsFirst( UserEntity userEntity ){  // 是首次注册，保存信息
        Constans.u_id = userEntity.getU_id();
        Constans.u_account = userEntity.getU_account();
        Constans.u_password = userEntity.getU_password();
    }
    public void initConstants( UserEntity userEntity){ // 非首次注册,保存信息
        Constans.u_id = userEntity.getU_id();
        Constans.u_account = userEntity.getU_account();
        Constans.u_password = userEntity.getU_password();
        Constans.u_username = userEntity.getU_username();
        Constans.u_character = userEntity.getU_character();
        Constans.u_spirit = userEntity.getU_spirit();
        Constans.u_head = userEntity.getU_head();
        Constans.account_select = userEntity.getAccount_select();
        Constans.character_select = userEntity.getCharacter_select();
        Constans.spirit_select = userEntity.getSpirit_select();
        Constans.head_select = userEntity.getHead_select();
        Constans.u_first_time = userEntity.getU_first_time();
        Constans.u_last_time = userEntity.getU_last_time();
    }
    class Runner extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LoginActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // userName是否null ，

                }
            });
        }
    }

    /**
     *  自动登录：
     *  获取sharePreferences 存在就自动跳转。让Constants里变量等于Sp即可
     *
     *  在WelCome里获取SharePreferences
     *  login分两种情况
     * */

    public void initSharedPreferencesFirst(UserEntity userEntity){
        SharedPreferences sharedPreferences = this.getSharedPreferences("user",MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putInt("u_id",userEntity.getU_id());
        edit.putString("u_account",userEntity.getU_account());
        edit.putString("u_password",userEntity.getU_password());
    }

    private static final String TAG = "LoginActivity";
}